from django.db import models, router

from .deletion import BaseModelCollector
from .manager import BaseModelManager


class BaseModel(models.Model):
    """模型的抽象基类"""

    create_time = models.DateTimeField(auto_now_add=True, help_text="创建时间")
    update_time = models.DateTimeField(auto_now=True, help_text="修改时间")
    deleted = models.BooleanField(default=False, help_text="删除状态")

    objects = BaseModelManager()

    class Meta:
        abstract = True

    class OwnMeta:
        """自定义的元属性(Meta中不让添加)"""
        del_cond = {'deleted': False}  # 等价于 Model.objects.filter(deleted=False).delete()
        del_opt = {'deleted': True}  # 等价于 Model.deleted=True

    def delete(self, using=None, keep_parents=False):
        """逻辑删除"""
        using = using or router.db_for_write(self.__class__, instance=self)
        assert self.pk is not None, (
                "%s object can't be deleted because its %s attribute is set to None." %
                (self._meta.object_name, self._meta.pk.attname)
        )

        # `BaseModelCollector`的效果：
        # 一个对象被逻辑删除时，关联它的对象也会被逻辑删除
        collector = BaseModelCollector(using=using)
        collector.collect([self], keep_parents=keep_parents)
        return collector.delete()

    def destroy(self, using=None, keep_parents=False):
        """物理删除"""
        return super().delete(using, keep_parents)
